package com.app.module.camera.renderer.group

import android.content.res.Resources
import com.app.module.camera.renderer.GLRenderer
import com.app.module.camera.renderer.base.DefaultRenderer

open class GroupRenderer : DefaultRenderer {

    private val mGroup: MutableList<GLRenderer>
    private var isDrawing = false;

    constructor(resource: Resources) : super(resource){
        mGroup = arrayListOf()
    }

    fun addRenderer(renderer: GLRenderer){
        addRenderer(mGroup.size, renderer)
    }

    fun addRenderer(idx:Int ,renderer: GLRenderer){
        if (isDrawing) {
            runOnGLThread(Runnable {
                renderer.create()
                renderer.sizeChanged(mWidth, mHeight)
                mGroup.add(idx, renderer)
            })
        } else {
            mGroup.add(idx, renderer)
        }
    }

    fun removeRenderer(index: Int) {
        if(isDrawing){
            runOnGLThread(Runnable {
                mGroup.removeAt(index).also {
                    it.destroy()
                }
            })
        }else{
            mGroup.removeAt(index)
        }
    }

    fun removeRenderer(renderer: GLRenderer){
        if(isDrawing){
            runOnGLThread(Runnable {
                if (mGroup.remove(renderer)) {
                    renderer.destroy()
                }
            })
        }else{
            mGroup.remove(renderer)
        }
    }

    fun get(index: Int): GLRenderer {
        return mGroup[index]
    }

    fun iterator(): Iterator<GLRenderer> {
        return mGroup.iterator()
    }

    fun isEmpty(): Boolean {
        return mGroup.isEmpty()
    }

    override fun create() {
        super.create()
        mGroup.forEach {
            it.create()
        }
    }

    override fun sizeChanged(width: Int, height: Int) {
        super.sizeChanged(width, height)
        mGroup.forEach {
            it.sizeChanged(width, height)
        }
    }

    override fun draw(texture: Int) {
        if(!isDrawing){
            isDrawing = true
        }
        var tempTextureId = texture
        mGroup.forEach {
            tempTextureId = it.drawToTexture(tempTextureId)
        }
        super.draw(tempTextureId)
    }
}
